package com.fac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fac.constant.ExceptionConstant;
import com.fac.dto.InspectionPlanCreateDTO;
import com.fac.dto.InspectionPlanPageQueryDTO;
import com.fac.entity.InspectionPlan;
import com.fac.entity.Users;
import com.fac.exception.BusinessException;
import com.fac.mapper.InspectionPlanMapper;
import com.fac.mapper.UsersMapper;
import com.fac.result.PageResult;
import com.fac.service.InspectionPlanService;
import com.fac.vo.InspectionPlanCreateVO;
import com.fac.vo.InspectionPlanVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class InspectionPlanServiceImpl implements InspectionPlanService {

    @Autowired
    private InspectionPlanMapper inspectionPlanMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public InspectionPlanCreateVO create(InspectionPlanCreateDTO createDTO) {
        // 查询管理员信息
        Users manager = usersMapper.selectById(createDTO.getManagerId());
        if (manager == null) {
            throw new BusinessException(ExceptionConstant.ADMIN_NOT_FOUND);
        }

        // 生成计划编号
        String planCode = generatePlanCode();

        try {
            // 创建计划
            InspectionPlan plan = InspectionPlan.builder()
                    .code(planCode)
                    .name(createDTO.getName())
                    .cycle(createDTO.getCycle())
                    .items(objectMapper.writeValueAsString(createDTO.getItems()))
                    .managerId(createDTO.getManagerId())
                    .status(1)
                    .build();

            // 保存计划
            inspectionPlanMapper.insert(plan);

            // 返回结果
            return InspectionPlanCreateVO.builder()
                    .planId(plan.getPlanId())
                    .code(plan.getCode())
                    .name(plan.getName())
                    .cycle(plan.getCycle())
                    .build();
        } catch (JsonProcessingException e) {
            log.error("巡检项目序列化失败", e);
            throw new BusinessException(ExceptionConstant.INSPECTION_ITEMS_FORMAT_ERROR);
        }
    }

    @Override
    public PageResult pageQuery(InspectionPlanPageQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<InspectionPlan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(queryDTO.getStatus() != null, InspectionPlan::getStatus, queryDTO.getStatus())
                .orderByDesc(InspectionPlan::getCreatedAt);

        // 分页查询
        Page<InspectionPlan> page = inspectionPlanMapper.selectPage(
                new Page<>(queryDTO.getPage(), queryDTO.getSize()),
                wrapper
        );

        // 转换为VO
        List<InspectionPlanVO> voList = page.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return new PageResult(page.getTotal(), voList);
    }

    /**
     * 生成计划编号
     */
    private String generatePlanCode() {
        LocalDateTime now = LocalDateTime.now();
        String date = String.format("%tY%<tm%<td", now);

        // 查询当天最大序号
        String prefix = "P" + date;
        LambdaQueryWrapper<InspectionPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(InspectionPlan::getCode, prefix)
                .orderByDesc(InspectionPlan::getCode)
                .last("LIMIT 1");

        InspectionPlan lastPlan = inspectionPlanMapper.selectOne(queryWrapper);

        int sequence = 1;
        if (lastPlan != null) {
            String lastCode = lastPlan.getCode();
            sequence = Integer.parseInt(lastCode.substring(9)) + 1;
        }

        return String.format("%s%03d", prefix, sequence);
    }

    /**
     * 转换为VO
     */
    private InspectionPlanVO convertToVO(InspectionPlan plan) {
        try {
            // 查询管理员信息
            Users manager = usersMapper.selectById(plan.getManagerId());

            // 解析巡检项目
            List<InspectionPlanCreateDTO.InspectionItem> items = objectMapper.readValue(
                    plan.getItems(),
                    objectMapper.getTypeFactory().constructCollectionType(
                            List.class,
                            InspectionPlanCreateDTO.InspectionItem.class
                    )
            );

            return InspectionPlanVO.builder()
                    .planId(plan.getPlanId())
                    .code(plan.getCode())
                    .name(plan.getName())
                    .cycle(plan.getCycle())
                    .managerName(manager != null ? manager.getRealName() : null)
                    .status(plan.getStatus())
                    .items(items)
                    .build();
        } catch (JsonProcessingException e) {
            log.error("巡检项目反序列化失败", e);
            throw new BusinessException(ExceptionConstant.INSPECTION_ITEMS_FORMAT_ERROR);
        }
    }
} 